﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraScheduler;
using DevExpress.XtraScheduler.Services;
using DevExpress.XtraScheduler.Commands;
using DevExpress.Utils.Menu;
using DevExpress.XtraScheduler.Drawing;

namespace QLTV.Forms.KeHoach
{
    public partial class frmLongPlanVessel : BaseForm
    {
        public frmLongPlanVessel()
        {
            InitializeComponent();
            this.schedulerStorage1.Appointments.CustomFieldMappings.Add(new AppointmentCustomFieldMapping("VesselID", "nVesselId"));
            this.schedulerStorage1.Appointments.CustomFieldMappings.Add(new AppointmentCustomFieldMapping("CrewID", "nCrewId"));
            this.schedulerStorage1.Appointments.CustomFieldMappings.Add(new AppointmentCustomFieldMapping("PlanID", "PlanID"));
            this.schedulerStorage1.Appointments.CustomFieldMappings.Add(new AppointmentCustomFieldMapping("nContract", "nContract"));
            this.schedulerStorage1.Appointments.CustomFieldMappings.Add(new AppointmentCustomFieldMapping("ShortName", "ShortName"));

        }

        private static Color getcolor(int grayScale)
        {
         
            return Color.FromArgb(grayScale, grayScale, grayScale);
        }
        private void addLabel(int number)
        {

            Random random = new Random();
            for (int i = 1; i <= number; i++)
            {
             
                AppointmentLabel lbl = new AppointmentLabel(getcolor(random.Next(255)),"", "");
                schedulerStorage2.Appointments.Labels.Add(lbl);
                schedulerStorage1.Appointments.Labels.Add(lbl);
            }
            
        }



        public int PlanID { get; set; }
        public bool isNew { get; set; }

        private void frmLongPlanVessel_Load(object sender, EventArgs e)
        {

            loadData();

        }
        public void loadData()
        {
            tblVesselTableAdapter.Fill(dsLongPlan.tblVessel);
            this.tblRankTableAdapter.Fill(this.dsLongPlan.tblRank);
            this.tblFlagTableAdapter.Fill(this.dsVessel.tblFlag);
            this.tblVesselGroupTableAdapter.Fill(this.dsVessel.tblVesselGroup);
            //gán màu ngẫu nhiên cho từng tàu
            addLabel(dsLongPlan.tblVessel.Rows.Count);
            
            if (isNew)
            {
                tblKeHoachBindingSource.AddNew();
                radioGroup1.SelectedIndex = 0;
                datePlanCreated.EditValue = DateTime.Now.Date;
                txtNguoiLap.EditValue = Program.EmployeeName;
                từDateEdit.EditValue = new DateTime(DateTime.Now.Year, 1, 1);
                đếnDateEdit.EditValue = new DateTime(DateTime.Now.Year + 1, 12, 30);
            }
            else
            {

                this.tblKeHoachTableAdapter.FillByID(this.dsLongPlan.tblKeHoach, PlanID);
                lbldate.Text = "Ngày chỉnh sửa";

                datePlanCreated.Properties.ReadOnly = true;
                datePlanCreated.DataBindings.RemoveAt(0);
                this.datePlanCreated.DataBindings.Add(new System.Windows.Forms.Binding("EditValue", this.tblKeHoachBindingSource, "Ngày chỉnh sửa", true));
                datePlanCreated.EditValue = DateTime.Now.Date;
                this.tblLongPlanVesselTableAdapter.FillBy(this.dsLongPlan.tblLongPlanVessel, PlanID);

                this.tblCurrentOnBoardTableAdapter.Fill(this.dsAssignment.tblCurrentOnBoard);

            }


            //set default 

            // _wait.ShouldCloseNow = true;
        }
        private void loadIntervalYear()
        {
            if (đếnDateEdit.EditValue != DBNull.Value && từDateEdit.EditValue != DBNull.Value)
            {
                if ((DateTime)đếnDateEdit.EditValue > (DateTime)từDateEdit.EditValue)
                {
                    schedulerControl1.LimitInterval.Start = (DateTime)từDateEdit.EditValue;
                    schedulerControl1.LimitInterval.End = (DateTime)đếnDateEdit.EditValue;
                    schedulerControl2.LimitInterval.Start = (DateTime)từDateEdit.EditValue;
                    schedulerControl2.LimitInterval.End = (DateTime)đếnDateEdit.EditValue;
                }

            }

        }


        private void schedulerStorage1_AppointmentsChanged(object sender, PersistentObjectsEventArgs e)
        {
            updateLongPlan();

        }
        private void updateLongPlan()
        {
            if (dxValidationProvider1.Validate())
            {
                tblKeHoachBindingSource.EndEdit();
                tblKeHoachTableAdapter.Update(dsLongPlan.tblKeHoach);

                tblLongPlanVesselBindingSource.EndEdit();
                this.tblLongPlanVesselTableAdapter.Update(dsLongPlan.tblLongPlanVessel);
                dsLongPlan.AcceptChanges();
                schedulerControl1.Refresh();

            }
            else
            {
                splitContainerControl1.Collapsed = false;
            }
        }

        private void schedulerStorage1_AppointmentsDeleted(object sender, PersistentObjectsEventArgs e)
        {
            updateLongPlan();
        }


        private void lookupVessel_EditValueChanged(object sender, EventArgs e)
        {

            if (lookupVessel.EditValue != DBNull.Value)
            {
                tblLongPlanVesselBindingSource.Filter = "nVesselId=" + (int)lookupVessel.EditValue;
                tblCurrentOnBoardBindingSource.Filter = "nVesselId=" + (int)lookupVessel.EditValue;

                schedulerControl1.ActiveView.ResourcesPerPage = 8;
                schedulerControl2.ActiveView.ResourcesPerPage = 8;
            }
            else
            {
                tblLongPlanVesselBindingSource.Filter = "";
                tblCurrentOnBoardBindingSource.Filter = "";
                schedulerControl1.ActiveView.ResourcesPerPage = 2;
                schedulerControl2.ActiveView.ResourcesPerPage = 2;
            }
        }

        private void splitContainerControl1_Panel1_Leave(object sender, EventArgs e)
        {
            splitContainerControl1.Collapsed = true;
        }

        private void cmdSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            updateLongPlan();
            alertControl1.Show(this, rm.GetString("sMessageCaption", myCultureInfo), rm.GetString("sMessageSuccess", myCultureInfo));
            this.Close();
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dsLongPlan.HasChanges())
            {
                if (XtraMessageBox.Show(rm.GetString("sHasChange", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                    updateLongPlan();
                
            }
            this.Close();
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show(rm.GetString("sConfirm", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
            {
                tblKeHoachBindingSource.RemoveCurrent();
                tblKeHoachBindingSource.EndEdit();
                tblKeHoachTableAdapter.Update(dsLongPlan.tblKeHoach);
                alertControl1.Show(this, rm.GetString("sMessageCaption", myCultureInfo), rm.GetString("sMessageSuccess", myCultureInfo));
                this.Close();
            }

        }



        private void từDateEdit_EditValueChanged(object sender, EventArgs e)
        {
            loadIntervalYear();
        }

        private void frmLongPlanVessel_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                updateLongPlan();
            }
        }

        private void schedulerControl2_SelectionChanged(object sender, EventArgs e)
        {
            
        }

        private void schedulerControl2_VisibleIntervalChanged(object sender, EventArgs e)
        {
            schedulerControl1.ActiveView.SetVisibleIntervals(schedulerControl2.ActiveView.GetVisibleIntervals());
        }

        private void lookupRank_SelectedIndexChanged(object sender, EventArgs e)
        {
            lookupRank1.SelectedIndex = lookupRank.SelectedIndex;
        }

        private void lookupRank1_SelectedIndexChanged(object sender, EventArgs e)
        {
            lookupRank.SelectedIndex = lookupRank1.SelectedIndex;
        }

        private void schedulerControl1_EditAppointmentFormShowing(object sender, AppointmentFormEventArgs e)
        {
            if (isNew)
            {
                if (XtraMessageBox.Show(rm.GetString("sInsertFirst", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    if (dxValidationProvider1.Validate())
                    {
                        tblKeHoachBindingSource.EndEdit();
                        tblKeHoachTableAdapter.Update(dsLongPlan.tblKeHoach);
                        isNew = false;
                    }
                    else
                    {
                        splitContainerControl1.Collapsed = false;
                        e.Handled = true;
                        return;
                    }
                }
                else
                {
                    e.Handled = true;
                    return;
                }
            }


            Appointment apt = e.Appointment;


            DevExpress.XtraScheduler.SchedulerControl control = (DevExpress.XtraScheduler.SchedulerControl)sender;
            if (control.Storage.Appointments.IsNewAppointment(apt) == true)
            {
                apt.CustomFields["nContract"] = schedulerControl1.SelectedInterval.Duration.Days / 29;
                if (lookupVessel.EditValue != null)
                {
                    apt.CustomFields["VesselID"] = (int)lookupVessel.EditValue;
                    apt.CustomFields["CrewID"] = "";
                }
                else
                {
                    //XtraMessageBox.Show(rm.GetString("sVesselChoice",myCultureInfo),rm.GetString("sMessageCaption",myCultureInfo), MessageBoxButtons.OK);
                    //lookupVessel.Focus();
                    //e.Handled = true;
                    //return;
                    apt.CustomFields["VesselID"] = 0;
                }
            }
            // Create a custom form.
            KeHoach.frmEditPlanPopup myForm = new KeHoach.frmEditPlanPopup((SchedulerControl)sender, apt, false);
            myForm.PlanID = PlanID;

            try
            {
                // Required for skins support.
                myForm.LookAndFeel.ParentLookAndFeel = schedulerControl1.LookAndFeel;
                e.DialogResult = myForm.ShowDialog();

                schedulerControl1.Refresh();
                e.Handled = true;
                this.tblLongPlanVesselTableAdapter.Update(dsLongPlan);
                dsLongPlan.AcceptChanges();

            }
            finally
            {
                myForm.Dispose();
            }
        }

        private void schedulerControl1_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            if (e.Menu.Id == DevExpress.XtraScheduler.SchedulerMenuItemId.DefaultMenu)
            {
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewAllDayEvent);
                //e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewRecurringAppointment);
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.SwitchViewMenu);
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.SwitchTimeScale);
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.TimeScaleVisible);
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.TimeScaleEnable);

                SchedulerMenuItem item = e.Menu.GetMenuItemById(SchedulerMenuItemId.NewAppointment);
                if (item != null) item.Caption = rm.GetString("sPlan", myCultureInfo);


                #region them mot command
                // Create a menu item for the Scheduler command.
                //ISchedulerCommandFactoryService service =
                //(ISchedulerCommandFactoryService)schedulerControl1.GetService(typeof(ISchedulerCommandFactoryService));
                //SchedulerCommand cmd = service.CreateCommand(SchedulerCommandId.SwitchToGroupByResource);
                //SchedulerMenuItemCommandWinAdapter menuItemCommandAdapter =
                //    new SchedulerMenuItemCommandWinAdapter(cmd);
                // Insert a new item into the Scheduler popup menu and handle its click event.
                //   e.Menu.Items.Add(new SchedulerMenuItem("Click me!", MyClickHandler));

                //DXMenuItem menuItem = new DXMenuItem("Lập kế hoạch", MyClickHandler) { BeginGroup = true };
                //e.Menu.Items.Add(menuItem);

                //e.Menu.MoveMenuItem(menuItem, 0); 
                #endregion
            }
        }

        private void schedulerControl1_VisibleIntervalChanged(object sender, EventArgs e)
        {
            //schedulerControl2.ActiveView.SetVisibleIntervals(schedulerControl1.ActiveView.GetVisibleIntervals());
        }

        private void lookupVessel_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            lookupVessel.EditValue = DBNull.Value;
        }

        private void schedulerControl2_MouseDown(object sender, MouseEventArgs e)
        {
            schedulerControl1.ActiveView.SetSelection(schedulerControl2.SelectedInterval, schedulerControl2.SelectedResource);
        }

        private void schedulerControl2_MouseUp(object sender, MouseEventArgs e)
        {

        }


    }
}